package com.jy.api.service.impl;

import com.jy.api.dao.OrderDao;
import com.jy.api.dao.ProductDao;
import com.jy.api.dao.StockTransactionDao;
import com.jy.api.domain.*;
import com.jy.api.service.StockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by lihu on 2018/2/1.
 */
@Service
public class StockServiceImpl implements StockService {
    @Autowired
    private StockTransactionDao stockTransactionDao;

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private ProductDao productDao;

    @Override
    @Transactional
    public void stockOutByOrderId(String orderId) {
        Order order = orderDao.findOne(orderId);
        List<Product> pro = new ArrayList<>();
        for (OrderItem item : order.getItems()) {
            if (null != item.getProductId()) {
                Product product = productDao.findOne(item.getProductId());
                if (product.isStockEnabled()) {
                    product.setQuantity(product.getQuantity() - item.getQuantity());
                    StockChangeTransaction transaction = new StockChangeTransaction(order.getId(),
                            order.getCreatorId(), order.getCreatorName(), item.getQuantity(),
                            product, StockType.STOCK_OUT, "");
                    stockTransactionDao.save(transaction);
                    pro.add(product);
                } else {
                    continue;
                }
            } else {
                List<Product> products = productDao.findBySetMealIdAndEnabled(item.getSetMealId(), true);
                for (Product p : products) {
                    if (p.isStockEnabled()) {
                        p.setQuantity(p.getQuantity() - (p.getSetMealQty() *item.getQuantity()));
                        StockChangeTransaction transaction = new StockChangeTransaction(order.getId(),
                                order.getCreatorId(), order.getCreatorName(), (p.getSetMealQty() *item.getQuantity()),
                                p, StockType.STOCK_OUT, "");
                        stockTransactionDao.save(transaction);
                        pro.add(p);
                    } else {
                        continue;
                    }
                }
            }
        }
        productDao.save(pro);
    }
}
